package cn.zysheep.strategy.factory;


import cn.zysheep.strategy.annotation.PayCode;
import cn.zysheep.strategy.service.IPay;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: PayFactory
 * @Author: lyw
 * @Date: 2023/1/12 16:08
 * @Description: 所有的Bean被成功装载，后处理Bean被检测并激活，所有Singleton Bean 被预实例化，ApplicationContext容器已就绪可用。
 */
@Component
public class PayFactory implements ApplicationListener<ContextRefreshedEvent> {

    private static final Map<String, IPay> PAY_MAP = new HashMap<>();

    /**
     * 获取对应实例Bean
     * @param type
     * @return
     */
    public static IPay getInstance(String type) {
        return PAY_MAP.get(type);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(PayCode.class);
        if (beansWithAnnotation !=null ) {
            beansWithAnnotation.forEach((k,v)->{
                PayCode payCodeAnn = v.getClass().getAnnotation(PayCode.class);
                PAY_MAP.put(payCodeAnn.value(), (IPay)v);
            });
        }
    }
}
